<template>
  <div id="advert" class="container">
    <div class="search">
      <el-form ref="searchForm" size="small" :model="searchForm" inline label-width="90px">
        <el-form-item label="广告名称：" prop="title">
          <el-input v-model="searchForm.title" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search(searchForm)">查 询</el-button>
          <el-button @click="reset(searchForm)">重 置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <h3 class="title"><span />广告管理</h3>
    <el-button type="primary" class="add" size="small" icon="el-icon-plus" style="margin-bottom:15px" @click="goAdd">添加</el-button>
    <!-- <el-button type="danger" size="small" icon="el-icon-delete" @click="Batchdelete">批量删除</el-button> -->
    <BouncedDialog :title="addForm.id?'编辑':'添加'" :dialog-show.sync="dialogShow" :width="50" class="advert">
      <el-form ref="addForm" :model="addForm" :rules="rules" inline class="addForm" label-width="100px">
        <!-- <el-form-item label="选择站点" prop="website_id">
          <el-select v-model="addForm.website_id" placeholder="请选择站点" @change="chooseWedsite">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.domain"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="广告形式" prop="type">
          <el-radio-group v-model="addForm.type" @change="chooseType">
            <el-radio :label="1">文字</el-radio>
            <el-radio :label="2">图片</el-radio>
            <el-radio :label="3">视频</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="广告名称" prop="title">
          <el-input v-model="addForm.title" />
        </el-form-item>
        <el-form-item label="广告链接" prop="url">
          <el-input v-model="addForm.url" placeholder="以‘http://’开头" />
        </el-form-item>
        <el-form-item v-if="addForm.type == 1" label="广告内容" prop="content">
          <el-input v-model="addForm.content" type="textarea" />
        </el-form-item>
        <el-form-item label="广告有效期" prop="expiration_date">
          <el-date-picker
            v-model="addForm.expiration_date"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
          />
        </el-form-item>
        <div v-if="addForm.type == 2 || addForm.type == 3">
          <el-form-item label="广告尺寸" prop="size">
            <el-input v-model="addForm.size" placeholder="例如：300X200" />
          </el-form-item>
          <el-form-item v-if="addForm.type == 2" size="small" label="广告图片:" prop="attachment_id">
            <div class="attachmentBtn">
              <el-upload
                :headers="myHeaders"
                class="avatar-uploader"
                :action="$store.getters.updateURL+'attachment/uploadAndSave'"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :data="{type:2}"
              >
                <!-- <img v-if="addForm.image_url" :src="imageUrl" class="avatar">
                <img v-else class="avatar" :src="require('../../images/icon1.png')" alt="">
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过1MB
                </div> -->
                <el-button size="small" type="primary" icon="el-icon-upload2">点击上传</el-button>
              </el-upload>
              <el-button
                size="small"
                class="blue"
                type="primary"
                icon="el-icon-s-unfold"
                @click="openList('image')"
              >选择附件</el-button>
            </div>
            <div class="imgBox">
              <img v-if="addForm.attachment_id" :src="imageUrl" class="attachmentImg">
            </div>
            <BouncedDialog title="选择附件" :append="true" :dialog-show.sync="dialogShow2" :width="70" class="attachment">
              <el-table
                v-loading="loading"
                v-el-table-infinite-scroll="load"
                :data="attachmentData"
                border
                :header-cell-style="{'text-align':'center','background-color':'#fff'}"
                :cell-style="{'text-align':'center'}"
              >
                <el-table-column label="ID" prop="id" width="60px" />
                <el-table-column label="预览">
                  <template slot-scope="scope">
                    <el-image
                      :src="scope.row.url"
                      alt=""
                      class="attachmentImg"
                      :preview-src-list="scope.row.imagelist"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="文件名" prop="name" />
                <el-table-column label="文件大小" prop="size" width="100px" />
                <el-table-column label="Mime类型" prop="mime_type" width="100px" />
                <el-table-column label="创建日期" prop="create_time" width="160px" />
                <el-table-column label="操作" width="120px">
                  <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-check" @click="choose(scope.row)">选择</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </BouncedDialog>
          </el-form-item>
          <el-form-item v-if="addForm.type == 3" label="广告视频:" prop="attachment_id">
            <el-upload
              :headers="myHeaders"
              class="avatar-uploader"
              :action="$store.getters.updateURL+'attachment/uploadAndSave'"
              :show-file-list="true"
              :on-success="handleAvatarSuccess"
              :data="{type:3}"
            >
              <el-button size="small" type="primary">选择视频</el-button>
            </el-upload>
          </el-form-item>
        </div>

        <div class="btn">
          <el-button @click="dialogShow = false">取 消</el-button>
          <el-button type="primary" @click="submit()">确 定</el-button>
        </div>
      </el-form>
    </BouncedDialog>
    <el-table
      :data="orderData"
      border
      stripe
      :header-cell-style="{'text-align':'center'}"
      :cell-style="{'text-align':'center'}"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" /> -->
      <el-table-column label="广告ID" prop="id" width="80" />
      <el-table-column label="广告名称" prop="title" show-overflow-tooltip />
      <el-table-column label="广告链接" prop="url" show-overflow-tooltip />
      <el-table-column label="广告形式" prop="type" width="120px">
        <template slot-scope="scope">
          <span v-if="scope.row.type == 1">文字</span>
          <span v-if="scope.row.type == 2">图片</span>
          <span v-if="scope.row.type == 3">视频</span>
        </template>
      </el-table-column>
      <el-table-column label="尺寸" prop="size" width="180px" />
      <el-table-column label="有效期" prop="expiration_date" width="180px" />
      <el-table-column label="操作" width="150px" fixed="right">
        <template slot-scope="scope">
          <el-button class="edit" size="mini" @click="editor(scope.row)">编辑</el-button>
          <el-button size="mini" class="dele" @click="del(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="page.currentPage"
      :page-sizes="page.pageSizes"
      :page-size="page.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total"
      :hide-on-single-page="page.total<page.size?true:false"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>
<script>
import advertApi from '@/api/market/advert.js'
import websiteApi from '@/api/website.js'
import attachmentApi from '@/api/system/attachment'
import { getToken } from '@/utils/auth'
import log from '@/api/log'
var token = 'Bearer ' + getToken()
export default {
  data() {
    return {
      attachmentLimit: 10,
      dialogShow2: false,
      attachmentData: [],
      imagelist: [],
      attachmentType: '',
      myHeaders: { Authorization: token },
      headers: {},
      imageUrl: '',
      imgUrl: this.$store.getters.updateURL,
      orderData: [], //
      dialogShow: false,
      options: [], // 站点下拉选项
      addForm: {
        type: 1
      },
      rules: {
        // website_id: [
        //   { required: 'true', message: '请选择站点', trigger: 'change' }
        // ],
        title: [
          { required: 'true', message: '请输入广告的名称', trigger: 'blur' }
        ],
        url: [
          { required: 'true', message: '请输入广告链接', trigger: 'blur' }
        ],
        content: [
          { required: 'true', message: '请输入广告内容', trigger: 'blur' }
        ],
        size: [
          { required: 'true', message: '请输入广告尺寸', trigger: 'blur' }
        ],
        attachment_id: [
          { required: 'true', message: '请上传广告图片/视频', trigger: 'blur' }
        ],
        expiration_date: [
          { required: 'true', message: '请输入广告有效期', trigger: 'blur' }
        ]
      },
      searchForm: {
        title: ''
      },
      page: {
        total: 0,
        currentPage: 1,
        size: 10,
        pageSizes: [10, 20, 30, 40]
      }, // 分页器
      val: {

      },
      id: '',
      loading: true
    }
  },
  created() {
    this.getList()
    this.getWebsiteList()
  },
  mounted() {
    // this.getTikets()
  },
  updated() {

  },
  methods: {
    load() {
      this.attachmentLimit += 10
      this.getAttachmentList()
    },
    // 打开附件弹窗
    openList(val) {
      this.attachmentType = val
      this.dialogShow2 = true
      this.getAttachmentList(val)
    },
    // 附件列表
    getAttachmentList() {
      const val = {
        limit: this.attachmentLimit,
        page: 1,
        type: 2
      }
      attachmentApi.attachmentList(val).then(res => {
        if (res.code == 0) {
          this.attachmentData = res.data
          this.loading = false
          this.imagelist = []
          // 获取每张图片的地址
          for (var x = 0;x < this.attachmentData.length;x++) {
            this.imagelist.push(this.attachmentData[x].url)
          }
          // 根据图片顺序（index）更改每张图片绑定的list的图片顺序
          for (var i = 0;i < this.attachmentData.length;i++) {
            var container = this.imagelist
            var frontArr = container.slice(0, i)
            var begindArr = container.slice(i, this.attachmentData.length)
            var list = begindArr.concat(frontArr)
            this.attachmentData[i].list = list
          }
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 选择附件
    choose(row) {
      if (this.attachmentType == 'image') {
        this.addForm.attachment_id = row.id
        this.imageUrl = row.url
      } else if (this.attachmentType == 'video') {
        this.addForm.banner = row.id
        this.banner = row.url
      }
      this.dialogShow2 = false
    },
    // 图片上传成功
    handleAvatarSuccess(res, file) {
      if (res.code == -200 || res.code == 0) {
        this.$forceUpdate()
        // this.addForm.image_url = res.data.url
        this.imageUrl = res.data.url
        this.addForm.attachment_id = res.data.id
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
      }
      return (isJPG || isPNG) && isLt2M
    },
    // 全选
    handleSelectionChange(val) {

    },
    // 批量删除
    Batchdelete() {

    },
    // 获取站点列表
    getWebsiteList() {
      websiteApi.websiteList().then(res => {
        this.options = res.data
      })
    },
    // 选择站点
    chooseWedsite(val) {
      this.$forceUpdate()
    },
    chooseType(val) {
      if (!this.addForm.id) {
        if (this.addForm.type == 1) {
          this.addForm = {
            type: val,
            title: '',
            url: '',
            content: '',
            expiration_date: ''
          }
        } else if (this.addForm.type == 2 || this.addForm.type == 3) {
          this.addForm = {
            type: val,
            title: '',
            url: '',
            expiration_date: '',
            size: '',
            attachment_id: ''
          }
        }
      }
    },
    // 新增
    goAdd() {
      this.addForm = {
        id: '',
        type: this.addForm.type,
        title: '',
        url: '',
        content: '',
        expiration_date: ''
      }
      this.dialogShow = true
    },
    // 编辑 获取广告详情
    editor(val) {
      advertApi.advertInfo({ id: val.id }).then(res => {
        if (res.code == 0) {
          if (res.data.type == 1) {
            this.addForm = {
              id: res.data.id,
              type: res.data.type,
              title: res.data.title,
              url: res.data.url,
              content: res.data.content,
              expiration_date: res.data.expiration_date
            }
          } else if (res.data.type == 2 || res.data.type == 3) {
            if (res.data.type == 2) {
              this.imageUrl = res.data.attachment.url
            }
            this.addForm = {
              id: res.data.id,
              type: res.data.type,
              title: res.data.title,
              url: res.data.url,
              attachment_id: res.data.attachment_id,
              expiration_date: res.data.expiration_date,
              size: res.data.size
            }
          }
        } else {
          this.$message.error(res.msg)
        }

        this.dialogShow = true
      })
    },
    submit() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          if (!this.addForm.id) {
            advertApi.advertSave({ ...this.addForm }).then(res => {
              if (res.code == 0) {
                this.$message.success(res.msg)
                this.dialogShow = false
                this.getList()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            advertApi.advertUpdate({ ...this.addForm }).then(res => {
              if (res.code == 0) {
                this.$message.success(res.msg)
                this.dialogShow = false
                this.getList()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        } else {
          this.$message.error('请填写必要信息')
        }
      })
    },

    // 删除
    del(row) {
      this.$confirm('此操作将永久删除该广告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        advertApi.advertDelete({ id: row.id }).then(res => {
          if (res.code == 0) {
            this.$message.success('已删除')
            this.getList()
          } else {
            this.$message.error('删除失败')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    search(val) {
      this.getList()
    },
    reset() {
      this.searchForm.title = ''
    },
    // 列表
    getList() {
      this.val.page = this.page.currentPage
      this.val.limit = this.page.size
      this.val.title = this.searchForm.title
      advertApi.advertList(this.val).then(res => {
        this.orderData = res.data
        this.page.total = res.count
      })
    },
    // 分页规格改变
    handleSizeChange(val) {
      this.page.size = val
      this.page.currentPage = 1
      this.getList()
    },
    // 分页点击
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.getList()
    }

  }
}
</script>
<style lang='scss'>
.attachment .el-dialog{
  .el-dialog__body{
    height: 600px;
  }
  .el-table{
    .attachmentImg{
      width: 60px;
      height: 60px;
    }
  }
  .el-button--primary{
    background-color:#f84311;
    border-color: #f84311;
    border-radius: 20px;
  }
}
#advert{
  // .advert{
  //   .el-select{
  //       width: calc(100% - 100px);
  //   }
  //   .el-date-editor.el-input{
  //     width: calc(100% - 100px);
  //   }
  // }
  .addForm .el-form-item{
    width: 100%;
  }
  .addForm .el-form-item__content{
      width: calc(100% - 100px);
  }
  .el-date-editor.el-input{
    width: 100%;
  }

}
</style>
<style scoped lang='scss'>
    .el-table{
      margin-bottom: 20px;
    }
    .search{
      min-width: 1350px;
      background-color: #fff;
      padding: 35px 30px 20px;
      border-radius: 5px;
      margin-bottom: 20px;
    }
    .avatar{
      max-width: 200px;
    }
</style>
